package newBee.class4;


import java.util.Arrays;

/**
 * https://leetcode.cn/problems/smallest-value-of-the-rearranged-number/description/
 * 重排数字的最小值
 */
public class Code02_smallestNumber {
    public static void main(String[] args) {
        int num = 310;
        System.out.println(minNumber(num));  // 输出 103

        int negativeNum = -103;
        System.out.println(minNumber(negativeNum));  // 输出 -310
    }


    public static long minNumber(long num) {
        if (num < 0) {
            char[] chars = Long.toString(-num).toCharArray();
            Arrays.sort(chars); // 对字符数组进行升序排序
            StringBuffer s = new StringBuffer(new String(chars));
            return Long.parseLong("-" + s.reverse());
        } else {
            char[] chars = Long.toString(num).toCharArray();
            Arrays.sort(chars); // 对字符数组进行升序排序
            // 如果最小的数字是 '0'，我们需要跳过前导零
            if (chars[0] == '0') {
                // 找到第一个非零数字
                for (int i = 1; i < chars.length; i++) {
                    if (chars[i] != '0') {
                        char x = chars[i];
                        chars[i] = chars[0];
                        chars[0] = x;
                        break;
                    }
                }
            }
            return Long.parseLong(new String(chars));
        }

    }
}
